package com.zsyh.changshang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import com.google.gson.Gson;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.zsyh.changshang.R;
import com.zsyh.changshang.adress.SelectAddresFinish;
import com.zsyh.changshang.adress.StringUtils;
import com.zsyh.changshang.adress.TestAdressPop;
import com.zsyh.changshang.basic.BaseActivity;
import com.zsyh.changshang.basic.MyAppliaction;
import com.zsyh.changshang.basic.PhoneContract;
import com.zsyh.changshang.basic.PhonePresenter;
import com.zsyh.changshang.basic.RetrofitHelper;
import com.zsyh.changshang.basic.StatusUtil;
import com.zsyh.changshang.basic.Viewable;
import com.zsyh.changshang.bean.PrivicesBean;
import com.zsyh.changshang.bean.RegisterBean;
import com.zsyh.changshang.data.DataApi;
import com.zsyh.changshang.util.CompressPhotoUtils;
import com.zsyh.changshang.util.EmptyUtil;
import com.zsyh.changshang.util.SPUtils;
import com.zsyh.changshang.util.ToastUtil;
import com.zsyh.changshang.weight.DialogManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;


@Viewable(presenter = PhonePresenter.class, layout = R.layout.regirstlayout)
public class RegisterActivity extends BaseActivity<PhoneContract.View, PhoneContract.Presenter> implements PhoneContract.View {

    @BindView(R.id.re_tob)
    RelativeLayout reTob;
    @BindView(R.id.tccs)
    TextView tccs;
    @BindView(R.id.csname)
    EditText csname;
    @BindView(R.id.tvlxr)
    TextView tvlxr;
    @BindView(R.id.lxr)
    EditText lxr;
    @BindView(R.id.tvfanshi)
    TextView tvfanshi;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.tvemail)
    TextView tvemail;
    @BindView(R.id.email)
    EditText email;
    @BindView(R.id.tvadress)
    TextView tvadress;
    @BindView(R.id.privance)
    TextView privance;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.quyu)
    TextView quyu;
    @BindView(R.id.delteadress)
    TextView delteadress;
    @BindView(R.id.xianxiadress)
    EditText xianxiadress;
    @BindView(R.id.tvyingye)
    TextView tvyingye;
    @BindView(R.id.scimage)
    ImageView scimage;
    @BindView(R.id.bntxiayibu)
    Button bntxiayibu;

    private DataApi dataApi;
    private String url;
    private DialogManager mDialogManager;
    private String provinceCodes, cityCodes, areaCodes;
    @Override
    public void init() {

        StatusUtil.setUseStatusBarColor(this, 0x00ffffff);
        StatusUtil.setSystemStatus(this, true, true);
        mDialogManager=new DialogManager();
        getProvince();
    }



    @OnClick({R.id.privance, R.id.city, R.id.quyu, R.id.scimage, R.id.bntxiayibu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.privance:

                TestAdressPop pop = new TestAdressPop();
                pop.setSelectAddresFinish(new SelectAddresFinish() {
                    @Override
                    public void finish(String provinceCode, String cityCode, String areaCode,String provincename,String cityname,String areaname) {
                        provinceCodes = provinceCode;
                        cityCodes = cityCode;
                        areaCodes = areaCode;
                        privance.setText(provincename+cityname+areaname);
                    }
                });
                pop.setAddress(provinceCodes, cityCodes, areaCodes);
                pop.show(getFragmentManager(), "address");
                break;
            case R.id.city:
                break;
            case R.id.quyu:
                break;
            case R.id.scimage:
                Album.camera(this)
                        .image()
                        .onResult(new Action<String>() {
                            @Override
                            public void onAction(@NonNull String result) {
                                url=result;
                                Glide.with(MyAppliaction.getContext()).load(result).into(scimage);

                            }
                        })
                        .onCancel(new Action<String>() {
                            @Override
                            public void onAction(@NonNull String result) {
                                //Toast.makeText(MyAppliaction.getContext(), R.string.canceled, Toast.LENGTH_LONG).show();
                            }
                        })
                        .start();

                break;
            case R.id.bntxiayibu:
                if (EmptyUtil.isEmpty(csname.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入厂家名称");
                    return;
                }

                if (EmptyUtil.isEmpty(lxr.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入联系人姓名");
                    return;
                }

                if (EmptyUtil.isEmpty(phone.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入手机号");
                    return;
                }else {
                   if(isPhoneNumber(phone.getText().toString())==false){
                       ToastUtil.showS(MyAppliaction.getContext(), "请填写正确的手机号码");
                       return;
                   }
                }

                if (EmptyUtil.isEmpty(email.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入邮箱地址");
                    return;
                }else{
                    if(StringUtils.checkEmailAddress(email.getText().toString())==false){
                        ToastUtil.showS(MyAppliaction.getContext(), "请输入正确的邮箱");
                        return;
                    }
                }

                if (EmptyUtil.isEmpty(areaCodes)) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请选择省市县");
                    return;
                }

                if (EmptyUtil.isEmpty(xianxiadress.getText().toString())) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请输入详细地址");
                    return;
                }

                if (EmptyUtil.isEmpty(url)) {
                    ToastUtil.showS(MyAppliaction.getContext(), "请上传营业执照");
                    return;
                }

                RegisterBean bean=new RegisterBean();
                bean.setFactory_name(csname.getText().toString());
                bean.setFactory_person(lxr.getText().toString());
                bean.setFactory_phone(phone.getText().toString());
                bean.setFactory_area(areaCodes);
                bean.setFactory_address(xianxiadress.getText().toString());
                bean.setFactory_email(email.getText().toString());
                Log.e("zhucedata",bean.toString());
                List<String> list=new ArrayList<>();
                list.add(url);
                regist(bean.toString(),list);

                break;
        }
    }


    public void regist(final String data, List<String> lists){
        mDialogManager.showLoadingDialogFragment(getSupportFragmentManager());
        dataApi = RetrofitHelper.getInstance().getRetrofit().create(DataApi.class);

        new CompressPhotoUtils().CompressPhoto(this, lists, new CompressPhotoUtils.CompressCallBack() {
            @Override
            public void success(List<String> listc) {
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM);//表单类型
                //多张图片
                for (int i = 0; i < listc.size(); i++) {
                    Log.e("cangshuimage",listc.get(i)+"");
                    File file = new File(listc.get(i));//filePath 图片地址
                    RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                    builder.addFormDataPart("files" + i, file.getName(), imageBody);//"imgfile"+i 后台接收图片流的参数名

                }
                List<MultipartBody.Part> parts = builder.build().parts();
                dataApi.Rigust(data,parts)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<ResponseBody>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    String body=responseBody.string();
                                    Log.e("zhuce",body+"");
                                    mDialogManager.hideLoadingDialogFragment();
                                    JSONObject jsonObject=new JSONObject(body);
                                    if(jsonObject.getString("errorCode").equals("0")){
                                        RegisterActivity.this.finish();
                                    }else{
                                        ToastUtil.showS(MyAppliaction.getContext(),jsonObject.getString("msg"));
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }

                            @Override
                            public void onError(Throwable e) {
                                mDialogManager.hideLoadingDialogFragment();
                            }

                            @Override
                            public void onComplete() {

                            }
                        });


            }
        });

    }










    public void getProvince() {
        dataApi = RetrofitHelper.getInstance().getRetrofit().create(DataApi.class);
        dataApi.getProvince()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String body = responseBody.string();
                            Log.e("bodyAdress", body);
                            JSONObject jsonObject = new JSONObject(body);
                            String errorCode = jsonObject.getString("errorCode");
                            if (errorCode.equals("0")) {
                                Log.e("logs", "走这一步");
                                Gson gson = new Gson();
                                PrivicesBean privicesBean = gson.fromJson(body, PrivicesBean.class);
                                SPUtils.put(RegisterActivity.this, "shenb", privicesBean.toString());

                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("bodyAdresserror", e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
